# -*- coding: utf-8 -*-
from nmj.sqlite.base_item import BaseNmjDB
from nmj.sqlite.tablesv2 import *
import logging
import os
import sqlite3

_LOGGER = logging.getLogger(__name__)
NMJ_MOVIE_TYPE = 1
NMJ_SERIE_TYPE = 2
NMJ_EPISODE_TYPE = 3
NMJ_SEASON_TYPE = 5



NMJ_VIDEO_TITLE_TYPE_ATTR = 'TITLE_TYPE'
NMJ_VIDEO_GENRE_ATTR = 'GENRE'

NMJ_GENRE_DOCUMENTARY_OR_SHORT = 0
NMJ_GENRE_MOVIE = 1

DIRECTOR = "DIRECTOR"

# TODO: set this in a config file
ignored_sort_tokens = [
	u"à",
	u"le",
	u"la",
	u"l'",
	u"de",
	u"du",
	u"d'",
	u"the",
	u"an",
	u"a",
]

extension_to_system = {
	".mkv" : "Matroska",
	".avi" : "AVI",
}

class NMJDBv2(BaseNmjDB):
	isolation_level = "DEFERRED"
	def __init__(self, library_path):
		super(NMJDBv2, self).__init__(library_path)
		self.connection.isolation_level = self.isolation_level
		self.videos = Videos.load(self.cursor)
		self.actors_cache = {}


	def purge(self):
		for table in Shows, ShowsGenres, ShowsKeywords, ShowsPersons, ShowsVideos, ShowGroups, \
				ShowGroupsShows, Videos, VideoBookmarks, VideoSubtitles, VideoGenres, VideoPersons, \
				VideoPosters, VideoProperties, Episodes, Synopsises:
			table.purge(self.cursor)
		self.connection.commit()

	def _get_sortable_title(self, title):
		for prefix in ignored_sort_tokens:
			if title.startswith(prefix):
				return title[len(prefix):]
		return title


	def insert_movie(self, movie):
		if movie.is_movie():
			_LOGGER.info("Inserting movie %s", movie)
			self.__insert_movie(movie)
		else:
			_LOGGER.info("Inserting episode %s", movie)
			self.__insert_episode(movie)
		self.connection.commit()

	def __insert_episode(self, movie):
		pass

	def __insert_movie(self, movie):
		show_db_id = Shows.insert(
			self.cursor,
			title=movie.title,
			search_title=movie.title,
			ttid=movie.imdb_id,
			update_state=3, # FIXME: Don't know what it means (probably "updated")
			release_date=getattr(movie, "release_date", "9999-01-01"),
			rating=getattr(movie, "rating", ""),
			title_type=NMJ_MOVIE_TYPE
		)
		video_id = Videos.insert(
			self.cursor,
			path=movie.path,
			file_type=3,
			scan_dir_id=1,
			update_state=2,
		)
		VideoPosters.insert(
			self.cursor,
			poster=self.to_nmj_path(movie.poster.filepath),
			thumbnail=self.to_nmj_path(movie.poster.thumbpath),
			wallpaper=self.to_nmj_path(movie.fanart.filepath),
		)
		ShowsVideos.insert(
			self.cursor,
			shows_id=show_db_id,
			videos_id=video_id
		)
		return show_db_id

# 	def update_show_total_item(self, show_db_id):
# 		show = Show.load(self.cursor, show_id=show_db_id)[0]
# 		nb_items = show.update_total_item(self.cursor)
# 		if nb_items == 0:
# 			show.delete(self.cursor)
# 		self.connection.commit()
#
# 	def __insert_video(self, movie, cast, show_db_id):
# 		video_db_id = Video.insert(
# 			self.cursor,
# 			path=movie.path,
# 			title=getattr(movie, "episode_title", None) or movie.title,
# 			search_title=movie.title,
# 			size=movie.size,
# 			ttid=movie.imdb_id,
# 			detail_poster=self.to_nmj_path(movie.poster.filepath),
# 			wallpaper=self.to_nmj_path(movie.fanart.filepath),
# 			update_state=3, # FIXME: Don't know what it means (probably "updated")
# 			cast_id=cast,
# 			show_id=show_db_id,
# 			season=getattr(movie, "season", ""),
# 			episode=getattr(movie, "episode", ""),
# 			release_date=getattr(movie, "release_date", "9999-01-01"),
# 			runtime=getattr(movie, "runtime", ""),
# 			rating=getattr(movie, "rating", ""),
# 		)
# 		VideoSynopsis.insert(self.cursor,
# 			content=movie.synopsis,
# 			video_id=video_db_id,
# 			show_id=show_db_id
# 		)
# 		VideoAttr.insert(
# 			self.cursor,
# 			video_id=video_db_id,
# 			type=NMJ_VIDEO_TITLE_TYPE_ATTR,
# 			value="feature",
# 		)
# 		return video_db_id
#
# 	def __insert_show(self, movie, cast):
# 		searching_constraints = {}
# 		if movie.imdb_id:
# 			searching_constraints["ttid"] = movie.imdb_id
# 		else:
# 			searching_constraints["title"] = movie.title
#
# 		if movie.is_movie():
# 			type = NMJ_MOVIE_TYPE
# 		else:
# 			type = NMJ_EPISODE_TYPE
#
# 		show_db_id = Shows.insert(
# 			self.cursor,
# 			title=movie.title,
# 			search_title=movie.title,
# 			ttid=movie.imdb_id,
# 			update_state=3, # FIXME: Don't know what it means (probably "updated")
# 			release_date=getattr(movie, "release_date", "9999-01-01"),
# 			rating=getattr(movie, "rating", ""),
# 			title_type=type
# 		)
# 		return show_db_id

	def create_db(self):
		_LOGGER.info("Creating database...")
		os.makedirs(os.path.dirname(self.media_db_path))
		conn = sqlite3.connect(self.media_db_path)
		conn.isolation_level = self.isolation_level
		cursor = conn.cursor()
		for table in ALL_TABLES:
			_LOGGER.debug("create table %s", table)
			table().create(cursor)
		DbVersion.insert(cursor, version="2.0.0")
		ScanDirs.insert(cursor, directory="LOCAL_DIR", name="LOCAL_NAME", scan_time="2010-11-11 13:11:42", size=1807172)
		ScanSystem.insert(cursor, type="RUNNING_STATUS", value="0")
		ScanSystem.insert(cursor, type="UPDATING_STAGE", value="5")
		conn.commit()
		cursor.close()
		conn.close()
		_LOGGER.info("Database creation done")


if __name__ == "__main__":
# 	import sys, pprint, re
	connection = sqlite3.connect("./sqlite/media.db") # give here the media.db
	connection.text_factory = str
	cursor = connection.cursor()
	# pprint.pprint(get_all_table_names(cursor))
	for table in ALL_TABLES:
		print 50 * "*", table
		items = table.load(cursor)
		for item in items:
			for attr in dir(item):
				if attr.startswith("__"):
					continue
				print "%s : %s" % (attr, getattr(item, attr))
	# fields = get_table_details(cursor, "VIDEO")[0][4].split("(")[1][:-1].split(", ")
	# pprint.pprint( "".join(['"%s", '%field.split(" ")[0] for field in fields]))
	# print get_DB_version(cursor)
	# print select(cursor, "SELECT TITLE, TOTAL_ITEM, SHOW_TYPE, TOTAL_EPISODES FROM SHOW")
	# videos = Video.load(cursor)
	# for attr in dir(videos[0]):
	# 	print "%s : %s" % (attr, getattr(videos[0], attr))
# 	for video in videos:
# 		print video, dir(video)

	# shows = Show.load(cursor)
	# for show in shows:
		# print show
